import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '我的记账本',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.blue,
          secondary: Colors.blueAccent,
        ),
        useMaterial3: true,
        cardTheme: CardTheme(
          elevation: 2,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
        floatingActionButtonTheme: const FloatingActionButtonThemeData(
          elevation: 4,
        ),
      ),
      home: const MyHomePage(title: '我的记账本'),
    );
  }
}

// 添加类别枚举
enum ExpenseCategory {
  dining('餐饮费'),
  material('材料费'),
  equipment('设备费'),
  meeting('会议费'),
  other('其他');

  final String label;
  const ExpenseCategory(this.label);
}

// 更新 Transaction 类
class Transaction {
  final String title;
  final double amount;
  final DateTime date;
  final bool isExpense;
  final ExpenseCategory category;  // 新增类别
  final String note;  // 新增备注
  bool isReimbursed;

  Transaction({
    required this.title,
    required this.amount,
    required this.date,
    required this.isExpense,
    required this.category,  // 新增
    required this.note,     // 新增
    this.isReimbursed = false,
  });
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final List<Transaction> _transactions = [];
  final _titleController = TextEditingController();
  final _amountController = TextEditingController();
  final _noteController = TextEditingController();
  bool _isExpense = true;
  ExpenseCategory _selectedCategory = ExpenseCategory.dining;  // 默认类别

  void _addTransaction() {
    final title = _titleController.text;
    final amount = double.tryParse(_amountController.text) ?? 0.0;
    final note = _noteController.text;

    if (title.isEmpty || amount <= 0) {
      return;
    }

    setState(() {
      _transactions.add(
        Transaction(
          title: title,
          amount: amount,
          date: DateTime.now(),
          isExpense: _isExpense,
          category: _selectedCategory,  // 新增
          note: note,                   // 新增
        ),
      );
    });

    _titleController.clear();
    _amountController.clear();
    _noteController.clear();
    Navigator.pop(context);
  }

  double get _totalBalance {
    return _transactions.fold(0.0, (sum, tx) {
      if (tx.isReimbursed) {
        return sum;
      }
      if (tx.isExpense) {
        return sum - tx.amount;
      }
      return sum + tx.amount;
    });
  }

  void _showAddTransactionDialog() {
    showDialog(
      context: context,
      builder: (ctx) => StatefulBuilder(
        builder: (context, setDialogState) => AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          title: const Text(
            '添加新记录',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                TextField(
                  controller: _titleController,
                  decoration: InputDecoration(
                    labelText: '标题',
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    filled: true,
                    fillColor: Colors.grey[50],
                  ),
                ),
                const SizedBox(height: 16),
                TextField(
                  controller: _amountController,
                  decoration: InputDecoration(
                    labelText: '金额',
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    filled: true,
                    fillColor: Colors.grey[50],
                    prefixText: '￥',
                  ),
                  keyboardType: const TextInputType.numberWithOptions(decimal: true),
                ),
                const SizedBox(height: 16),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(color: Colors.grey.shade400),
                    color: Colors.grey[50],
                  ),
                  child: DropdownButtonHideUnderline(
                    child: DropdownButton<ExpenseCategory>(
                      isExpanded: true,
                      value: _selectedCategory,
                      items: ExpenseCategory.values.map((category) {
                        return DropdownMenuItem(
                          value: category,
                          child: Text(category.label),
                        );
                      }).toList(),
                      onChanged: (value) {
                        setDialogState(() {
                          _selectedCategory = value!;
                        });
                      },
                    ),
                  ),
                ),
                const SizedBox(height: 16),
                TextField(
                  controller: _noteController,
                  decoration: InputDecoration(
                    labelText: '备注',
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    filled: true,
                    fillColor: Colors.grey[50],
                  ),
                  maxLines: 3,
                ),
                const SizedBox(height: 24),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Expanded(
                      child: ElevatedButton(
                        onPressed: () {
                          setDialogState(() => _isExpense = true);
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: _isExpense ? Colors.red.shade100 : Colors.grey.shade100,
                          foregroundColor: _isExpense ? Colors.red : Colors.grey,
                          padding: const EdgeInsets.symmetric(vertical: 12),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                        child: const Text('支出', style: TextStyle(fontSize: 16)),
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: ElevatedButton(
                        onPressed: () {
                          setDialogState(() => _isExpense = false);
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: !_isExpense ? Colors.green.shade100 : Colors.grey.shade100,
                          foregroundColor: !_isExpense ? Colors.green : Colors.grey,
                          padding: const EdgeInsets.symmetric(vertical: 12),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                        child: const Text('收入', style: TextStyle(fontSize: 16)),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: Text('取消', style: TextStyle(color: Colors.grey[600])),
            ),
            ElevatedButton(
              onPressed: _addTransaction,
              style: ElevatedButton.styleFrom(
                backgroundColor: Theme.of(context).colorScheme.primary,
                foregroundColor: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              child: const Text('添加'),
            ),
          ],
        ),
      ),
    );
  }

  void _toggleReimbursementStatus(int index) {
    setState(() {
      _transactions[index].isReimbursed = !_transactions[index].isReimbursed;
    });
  }

  @override
  Widget build(BuildContext context) {
    double unreimbursedTotal = _transactions.where((tx) => !tx.isReimbursed).fold(
      0.0,
      (sum, tx) => tx.isExpense ? sum - tx.amount : sum + tx.amount,
    );
    
    double reimbursedTotal = _transactions.where((tx) => tx.isReimbursed).fold(
      0.0,
      (sum, tx) => tx.isExpense ? sum - tx.amount : sum + tx.amount,
    );

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.primary,
        foregroundColor: Colors.white,
        elevation: 2,
        title: Text(widget.title),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(70),
          child: Container(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                Text(
                  '当前余额: ￥${unreimbursedTotal.toStringAsFixed(2)}',
                  style: const TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
                const SizedBox(height: 4),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.monetization_on,  // 使用金币图标
                      size: 16,
                      color: Colors.amber[300],  // 金色
                    ),
                    const SizedBox(width: 4),
                    Text(
                      '已报销: ',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.amber[100],
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    Text(
                      '￥${reimbursedTotal.abs().toStringAsFixed(2)}',
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.amber[300],
                        fontWeight: FontWeight.bold,
                        shadows: [
                          Shadow(
                            color: Colors.black.withOpacity(0.3),
                            offset: const Offset(0, 1),
                            blurRadius: 2,
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(width: 4),
                    Icon(
                      Icons.monetization_on,  // 对称放置另一个金币图标
                      size: 16,
                      color: Colors.amber[300],  // 金色
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
      body: _transactions.isEmpty
          ? Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.account_balance_wallet_outlined,
                    size: 64,
                    color: Colors.grey[400],
                  ),
                  const SizedBox(height: 16),
                  Text(
                    '还没有任何记录',
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.grey[600],
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    '点击右下角的按钮添加新记录',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey[400],
                    ),
                  ),
                ],
              ),
            )
          : ListView.builder(
              padding: const EdgeInsets.all(16),
              itemCount: _transactions.length,
              itemBuilder: (ctx, index) {
                final tx = _transactions[index];
                return _buildTransactionItem(tx, index);
              },
            ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _showAddTransactionDialog,
        icon: const Icon(Icons.add),
        label: const Text('添加记录'),
      ),
    );
  }

  Widget _buildTransactionItem(Transaction tx, int index) {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      child: Column(
        children: [
          ListTile(
            contentPadding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
            leading: CircleAvatar(
              radius: 24,
              backgroundColor: tx.isReimbursed
                  ? Colors.grey.shade200
                  : (tx.isExpense ? Colors.red.shade50 : Colors.green.shade50),
              child: Icon(
                tx.isExpense ? Icons.remove : Icons.add,
                color: tx.isReimbursed
                    ? Colors.grey
                    : (tx.isExpense ? Colors.red : Colors.green),
                size: 28,
              ),
            ),
            title: Row(
              children: [
                Expanded(
                  child: Text(
                    tx.title,
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                      decoration: tx.isReimbursed ? TextDecoration.lineThrough : null,
                      color: tx.isReimbursed ? Colors.grey : Colors.black87,
                    ),
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: Colors.grey[100],
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    tx.category.label,
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[600],
                    ),
                  ),
                ),
              ],
            ),
            subtitle: Text(
              '${tx.date.year}-${tx.date.month.toString().padLeft(2, '0')}-${tx.date.day.toString().padLeft(2, '0')}\n${tx.isReimbursed ? "已报销" : "未报销"}',
              style: TextStyle(color: Colors.grey[600]),
            ),
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  '${tx.isExpense ? "-" : "+"}￥${tx.amount.toStringAsFixed(2)}',
                  style: TextStyle(
                    fontSize: 16,
                    color: tx.isReimbursed
                        ? Colors.grey
                        : (tx.isExpense ? Colors.red : Colors.green),
                    fontWeight: FontWeight.bold,
                  ),
                ),
                IconButton(
                  icon: Icon(
                    tx.isReimbursed ? Icons.check_circle : Icons.check_circle_outline,
                    color: tx.isReimbursed ? Colors.grey : Colors.blue,
                  ),
                  onPressed: () => _toggleReimbursementStatus(index),
                ),
              ],
            ),
          ),
          if (tx.note.isNotEmpty)
            Padding(
              padding: const EdgeInsets.fromLTRB(64, 0, 16, 8),
              child: Row(
                children: [
                  Icon(Icons.note, size: 14, color: Colors.grey[400]),
                  const SizedBox(width: 4),
                  Expanded(
                    child: Text(
                      tx.note,
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[600],
                      ),
                    ),
                  ),
                ],
              ),
            ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _titleController.dispose();
    _amountController.dispose();
    _noteController.dispose();  // 新增
    super.dispose();
  }
}
